/*
 * Copyright (c) 2022 Huawei Technologies Co.,Ltd.
 *
 * GR is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *          http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 * -------------------------------------------------------------------------
 *
 * gr_session.h
 *
 *
 * IDENTIFICATION
 *    src/common/gr_session.h
 *
 * -------------------------------------------------------------------------
 */

#ifndef __GR_SESSION_H__
#define __GR_SESSION_H__

#include "cm_defs.h"
#include "cm_thread_pool.h"
#include "cm_date.h"
#include "cs_packet.h"
#include "cs_pipe.h"
#include "gr_defs.h"
#include "gr_au.h"
#include "gr_log.h"
#include "gr_protocol.h"
#include "gr_latch.h"
#include "gr_stats.h"
// #include "gr_shm.h"

#ifdef __cplusplus
extern "C" {
#endif

#define GR_INVALID_SESSIONID CM_INVALID_ID32
#define GR_MAX_LATCH_STACK_BOTTON 0
#define GR_MAX_LATCH_STACK_DEPTH 8
#define GR_LOCK_CLEAN_SLEEP_TIME 500
#define GR_SESSION_PAUSED_WAIT 50

#define GR_META_SYN_BG_TASK_NUM_MAX 4
#define GR_RECYLE_META_TASK_NUM_MAX 4

#define GR_SERVER_SESS_TIMEOUT 100

#define MAX_FILE_HASH_COUNT 100000
typedef enum st_gr_background_task_type {
    GR_RECOVERY_BACKGROUND_TASK = 0,
    GR_DELAY_CLEAN_BACKGROUND_TASK = 1,
    GR_HASHMAP_DYNAMIC_EXTEND_TASK = 2,
    GR_ALARM_CHECK_TASK = 3,
    GR_META_SYN_BG_TASK_BASE = 4,
    GR_META_SYN_BG_TASK_END = GR_META_SYN_BG_TASK_BASE + GR_META_SYN_BG_TASK_NUM_MAX,
    GR_RECYCLE_META_TASK_BASE = GR_META_SYN_BG_TASK_END,
    GR_RECYCLE_META_TASK_END = GR_RECYCLE_META_TASK_BASE + GR_RECYLE_META_TASK_NUM_MAX,
    GR_BACKGROUND_TASK_NUM = GR_RECYCLE_META_TASK_END,
} gr_background_task_type_e;

typedef struct st_gr_bg_task_info {
    uint32_t task_num_max;
    uint32_t my_task_id;
    uint32_t vg_id_beg;
    uint32_t vg_id_end;
    void *task_args;
} gr_bg_task_info_t;

typedef struct gr_cli_info {
    uint64 cli_pid;
    int64 start_time;
    char process_name[GR_FILE_NAME_BUFFER_SIZE + 1];
    uint32_t thread_id;
    uint64 connect_time;
} gr_cli_info_t;

typedef enum st_gr_latch_offset_type {
    GR_LATCH_OFFSET_INVALID = 0,
    GR_LATCH_OFFSET_UNIQ_ID,
    GR_LATCH_OFFSET_SHMOFFSET,
} gr_latch_offset_type_e;

typedef struct st_gr_latch_offset {
    gr_latch_offset_type_e type;
    union {
        uint32_t unique_id;
        uint64 shm_offset;
    } offset;
} gr_latch_offset_t;

typedef struct st_gr_latch_stack {
    gr_latch_offset_t latch_offset_stack[GR_MAX_LATCH_STACK_DEPTH];
    uint32_t stack_top;
    uint32_t stack_top_bak;
    gr_latch_shared_op_e op;
} gr_latch_stack_t;

typedef enum en_protocol_type {
    PROTO_TYPE_UNKNOWN = 0,
    PROTO_TYPE_GS = 1,
} protocol_type_t;

typedef enum en_gr_session_status {
    GR_SESSION_STATUS_IDLE = 0,
    GR_SESSION_STATUS_RUNNING,
    GR_SESSION_STATUS_PAUSING,
    GR_SESSION_STATUS_PAUSED,
} gr_session_status_t;

typedef struct st_gr_session {
    spinlock_t lock;  // for control current rw of the same session in server
    uint32_t id;
    bool32 is_closed;
    bool32 is_used;
    bool32 connected;
    bool32 reactor_added;
    cs_pipe_t pipe;
    gr_packet_t recv_pack;
    gr_packet_t send_pack;
    text_t send_info;  // send extra info, please use recv_pack.init_buf, len = 0 if no info ack
    ftid_t curr_dir;
    protocol_type_t proto_type;  // gauss or mysql (not realized)
    gr_cli_info_t cli_info;
    gr_latch_stack_t latch_stack;
    volatile uint64 curr_lsn;  // latest lsn generated by current session
    gr_audit_info_t audit_info;
    gr_session_status_t status;
    void *reactor;
    void *workthread_ctx;
    uint32_t client_version; /* client version */
    uint32_t proto_version;  /* client and server negotiated version */
    uint32_t objectid;
    gr_stat_ctx_t stat_ctx;
    bool8 is_direct;
    bool8 put_log;
    bool8 is_holding_hotpatch_latch;
    spinlock_t shm_lock;  // for control current rw of the same session in shm
    session_hash_mgr_t hash_mgr;
    // session-owned open file list for resource cleanup
    spinlock_t fd_lock;
    struct st_gr_session_fd_entry *fd_list_head;
    uint32_t fd_count;
} gr_session_t;

static inline char *gr_init_sendinfo_buf(char *input)
{
    return (input + sizeof(gr_packet_head_t) + sizeof(int32_t));
}

static inline void gr_session_end_stat(gr_session_t *session, timeval_t *begin_tv, gr_wait_event_e event)
{
    (void)session;  // 保留参数以避免接口变更
    gr_end_instance_stat(begin_tv, event);
}

typedef struct st_gr_session_ctrl {
    spinlock_t lock;
    bool32 is_inited;
    uint32_t used_count;
    uint32_t total;
    uint32_t alloc_sessions;
    gr_session_t **sessions;
} gr_session_ctrl_t;

extern gr_session_ctrl_t g_gr_session_ctrl;
status_t gr_init_session_pool(uint32_t max_session_num);
gr_session_ctrl_t *gr_get_session_ctrl(void);
status_t gr_create_session(const cs_pipe_t *pipe, gr_session_t **session);
void gr_destroy_session(gr_session_t *session);
void gr_destroy_session_inner(gr_session_t *session);
gr_session_t *gr_get_session(uint32_t sid);

// only used by api-client or by clean
bool32 gr_unlock_shm_meta_s_with_stack(gr_session_t *session, gr_shared_latch_t *shared_latch, bool32 is_try_lock);
void gr_clean_session_latch(gr_session_t *session, bool32 is_daemon);
uint32_t gr_get_uwression_startid(void);
uint32_t gr_get_recover_task_idx(void);
uint32_t gr_get_max_total_session_cnt(void);
uint32_t gr_get_delay_clean_task_idx(void);
uint32_t gr_get_alarm_check_task_idx(void);
typedef uint32_t (*gr_get_bg_task_idx_func_t)(uint32_t idx);
void gr_server_session_lock(gr_session_t *session);
void gr_server_session_unlock(gr_session_t *session);
gr_session_t *gr_get_reserv_session(uint32_t idx);
status_t init_session_hash_mgr(gr_session_t *session);
status_t update_file_hash(gr_session_t *session, uint32_t file_handle, const uint8_t *new_hash);
status_t get_file_hash(gr_session_t *session, uint32_t file_handle, uint8_t *curr_hash, uint8_t *prev_hash);
status_t generate_random_sha256(unsigned char *hash);

// session fd tracking APIs
typedef struct st_gr_session_fd_entry {
    int64 fd;
    uint64 ftid; // optional
    char file_name[GR_MAX_NAME_LEN];
    struct st_gr_session_fd_entry *next;
} gr_session_fd_entry_t;

status_t gr_session_fd_add(gr_session_t *session, int64 fd, uint64 ftid, const char *file_name);
bool32 gr_session_fd_remove(gr_session_t *session, int64 fd);
void gr_session_fd_close_all(gr_session_t *session);

#ifdef __cplusplus
}
#endif

#endif
